package com.homework.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.homework.dao.CourseUtil;
import com.homework.doamin.Course;
import com.homework.util.HomeworkUtil;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.sina.sae.storage.SaeStorage;
import com.sina.sae.util.SaeUserInfo;

public class UploadServlet extends HttpServlet {
	private ServletConfig config;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		SaeStorage saeSto=new SaeStorage();
		String realPath=SaeUserInfo.getSaeTmpPath()+ "/";
		
		RequestDispatcher dispach=req.getRequestDispatcher("/WEB-INF/uploadsuccess.jsp");
		int count=0;
		CourseUtil courseUtil=new CourseUtil();
		HomeworkUtil homeworkUtil=new HomeworkUtil();
		SmartUpload su=new SmartUpload();
		su.initialize(config, req, resp);
		
		try{
			su.setAllowedFilesList("jpeg,jpg,tiff,raw,bmp,gif,png");
			su.setTotalMaxFileSize(30000000);
			su.upload();
			Course course=courseUtil.getCourseByAcronym(su.getRequest().getParameter("course_acronym"));
			String ps1=new String(su.getRequest().getParameter("ps").trim().getBytes(),"utf-8");
			long homeworkId=courseUtil.add2Homework(course.getCourseId(),ps1);
			String newFileName=null;
			for(int i=0;i<su.getFiles().getCount();i++){
				com.jspsmart.upload.File myFile=su.getFiles().getFile(i);
				newFileName=homeworkUtil.getRandomFileName()+"."+myFile.getFileExt();
//				myFile.saveAs(this.getServletContext().getContextPath()+"\\picutres\\"+newFileName);
				myFile.saveAs(realPath+""+newFileName);
				saeSto.upload("pictures",realPath+newFileName+"", newFileName);
				
				courseUtil.add2Picture((int) homeworkId,newFileName);
				//myFile.saveAs(request.getServletContext().getContextPath())
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		dispach.forward(req, resp);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		this.config=config;
	}
	
}
